package com.feihong.yw189.activity.yonghuzhongxin.zhuanzhang;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.feihong.yw189.R;
import com.feihong.yw189.activity.base.BaseActivity;
import com.feihong.yw189.activity.yonghuzhongxin.AddmoeyDialog;
import com.feihong.yw189.adapter.MyBaseAdapter;
import com.feihong.yw189.app.App;
import com.feihong.yw189.global.RequestTools;
import com.feihong.yw189.http.HttpTools;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.message.LoginMessage;
import com.feihong.yw189.model.User.MessageItem;
import com.feihong.yw189.model.User.money.AccountDetailModel;
import com.feihong.yw189.model.User.money.AddMoneyModel;
import com.feihong.yw189.model.User.money.AddingMoneyDetailModel;
import com.holenzhou.pullrecyclerview.PullRecyclerView;
import com.holenzhou.pullrecyclerview.layoutmanager.XLinearLayoutManager;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class AddMoneyDetailActivity extends BaseActivity {
    @BindView(R.id.rl_goback)
    RelativeLayout ivBack;
    @BindView(R.id.txt_pagetitle)
    TextView txtPagetitle;
    @BindView(R.id.iv_lin)
    ImageView ivLin;
    @BindView(R.id.iv_confirm)
    TextView ivConfirm;
    @BindView(R.id.top_back_layout)
    LinearLayout topBackLayout;
    @BindView(R.id.pull_recycler_view)
    PullRecyclerView mPullRecyclerView;


    private MyBaseAdapter mAdapter;
    private int pageGlobal = 2;
    private AddMoneyModel.Data dataList;
    private AddMoneyModel.DataAccount dataAccountList;
    private int typeDefine;
    private Unbinder unbinder;

    AddmoeyDialog dialog = null;

    private int mDataSize = 0;
    @BindView(R.id.connect_net_error_layout)
    LinearLayout mNetErrorLayout;
    @BindView(R.id.null_data_layout)
    RelativeLayout mNullDataLayout;
    @BindView(R.id.null_data_layout_txt)
    TextView mNullDataWarningTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_money_detail);
        unbinder = ButterKnife.bind(this);

        Intent typeIntent = getIntent();
        typeDefine = typeIntent.getIntExtra("typeDefine", 0);


        initView();
        bindData();
    }

    @Override
    public void setTheme() {

    }

    private void initView() {
        setBackButtonFinish();
        ivLin.setVisibility(View.GONE);
        //收支明细
        if (typeDefine == 1) {
            setPageTitle("收支明细");
            //加款明细
        } else if (typeDefine == 3) {
            setPageTitle("加款记录");
        } else {
            showToast("该功能暂未开启!");
        }
    }

    private void bindData() {
        Map<String, Object> map = new HashMap();
        map.put("title", R.id.my_adding_money_title);
        map.put("time", R.id.my_adding_money_time);
        map.put("message", R.id.my_adding_money_message);
        map.put("subTitle", R.id.my_adding_money_subtitle);
        map.put("imageResId", R.id.my_adding_money_img);
//        map.put("imgUrl", R.id.sys_mess_img);

        // 初始化PullRecyclerView
        mPullRecyclerView.setLayoutManager(new XLinearLayoutManager(this));
        mAdapter = new MyBaseAdapter(this, R.layout.my_adding_money_item, map, typeDefine);
        mPullRecyclerView.setAdapter(mAdapter);

        mPullRecyclerView.setColorSchemeResources(R.color.appBlue);
        // 设置下拉刷新的旋转圆圈的颜色
        mPullRecyclerView.enablePullRefresh(true);
        // 开启下拉刷新，默认即为true，可不用设置


        //刷新监听
        mPullRecyclerView.setOnRecyclerRefreshListener(new PullRecyclerView.OnRecyclerRefreshListener() {
            @Override
            public void onPullRefresh() {
                mPullRecyclerView.enableLoadDoneTip(false, R.string.load_done_tip);
                // 开启数据全部加载完成时的底部提示，默认为false
                mPullRecyclerView.enableLoadMore(false);
                mAdapter.clear();
                //收支明细
                if (typeDefine == 1) {
                    // 下拉刷新网络请求
                    Callback.Cancelable drawCallBack = App.getApp().getHttpTools().addingMoneyList(1, 10, HttpTools.MY_MONEY_ACCOUNT, CallBackDown);
                    RequestTools.addNewRequest(AddMoneyDetailActivity.class.getName(), drawCallBack);
                    //加款明细
                } else if (typeDefine == 3) {
                    // 下拉刷新网络请求
                    Callback.Cancelable drawCallBack = App.getApp().getHttpTools().addingMoneyList(1, 10, HttpTools.MY_MONEY_YDETAIL, CallBackDown);
                    RequestTools.addNewRequest(AddMoneyDetailActivity.class.getName(), drawCallBack);

                } else {
                    showToast("该功能暂未开启!");
                }
            }

            @Override
            public void onLoadMore() {
                mPullRecyclerView.enableLoadDoneTip(false, R.string.load_done_tip);
                // 开启数据全部加载完成时的底部提示，默认为false
                //收支明细
                if (typeDefine == 1) {
                    Callback.Cancelable downCallBack = App.getApp().getHttpTools().addingMoneyList(pageGlobal, 10, HttpTools.MY_MONEY_ACCOUNT, callBackUp);
                    RequestTools.addNewRequest(AddMoneyDetailActivity.class.getName(), downCallBack);

                    //加款明细
                } else if (typeDefine == 3) {
                    Callback.Cancelable downCallBack = App.getApp().getHttpTools().addingMoneyList(pageGlobal, 10, HttpTools.MY_MONEY_YDETAIL, callBackUp);
                    RequestTools.addNewRequest(AddMoneyDetailActivity.class.getName(), downCallBack);


                } else {
                    showToast("该功能暂未开启!");
                }

            }
        });
        mPullRecyclerView.postRefreshing();

        // 通过adapter设置item的点击事件
        mAdapter.setOnItemClickListener(messageItem -> {
            if (isFastDoubleClick(OtherlastClickTime)) {
                return;
            }
            OtherlastClickTime = System.currentTimeMillis();
            if (dialog != null) dialog.cancel();

            //收支明细记录详情
            if (typeDefine == 1) {
                Callback.Cancelable clickCallBack = App.getApp().getHttpTools().addingMoneyDetail(messageItem.getId(), HttpTools.MY_MONEY_ACCOUNT_INFO, 1, callBackClick);
                RequestTools.addNewRequest(AddMoneyDetailActivity.class.getName(), clickCallBack);

                //获取加款记录详情
            } else if (typeDefine == 3) {
                Callback.Cancelable clickCallBack = App.getApp().getHttpTools().addingMoneyDetail(messageItem.getId(), HttpTools.MY_MONEY_YDETAIL_INFO, 3, callBackClick);
                RequestTools.addNewRequest(AddMoneyDetailActivity.class.getName(), clickCallBack);

            } else {
                showToast("该功能暂未开启!");
            }
        });
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    private void noDataLayout() {
        if (mNullDataLayout.getVisibility() == View.GONE) {
            mNetErrorLayout.setVisibility(View.GONE);
            mNullDataLayout.setVisibility(View.VISIBLE);
        }
    }

    private void normalDataLayout() {
        if (mNullDataLayout.getVisibility() == View.VISIBLE || mNetErrorLayout.getVisibility() == View.VISIBLE) {
            mNetErrorLayout.setVisibility(View.GONE);
            mNullDataLayout.setVisibility(View.GONE);
            mPullRecyclerView.setVisibility(View.VISIBLE);
        }
    }

    private void errorLayout() {
        if (mNetErrorLayout.getVisibility() == View.GONE) {
            mNetErrorLayout.setVisibility(View.VISIBLE);
            mNullDataLayout.setVisibility(View.GONE);
            mPullRecyclerView.setVisibility(View.GONE);
        }
    }

    //下拉获取信息
    RequestCallBack CallBackDown = new RequestCallBack() {
        @Override
        public void onSuccess(Object result) {
            if (activityIsDestory()) {
                return;
            }
            try {
                //json解析
                AddMoneyModel addMoneyModel = JSON.parseObject("" + result, AddMoneyModel.class);
                if (addMoneyModel != null) {
                    //有数据
                    if (addMoneyModel.status == 1) {
                        if (typeDefine == 1) {
                            dataAccountList = JSON.parseObject(addMoneyModel.data, AddMoneyModel.DataAccount.class);
                            //清除原数据,加载新数据,上拉加载
                            int pageSize = dataAccountList.list.size();
                            if (pageSize > 0) {
                                mDataSize = 0;
                                if (pageSize >= 10) {
                                    mPullRecyclerView.enableLoadMore(true);
                                }
                                MessageItem model;
                                //重置
                                pageGlobal = 2;
                                List<MessageItem> mDatas = new ArrayList<>();
                                for (AddMoneyModel.ListAccount message : dataAccountList.list) {
                                    model = new MessageItem();
                                    model.setTitle(message.log_type);
                                    model.setSubTitle(message.money);
                                    model.setTime(message.time);
                                    model.setMessage(message.type);
                                    model.setImageResId(accountMipmapId(message.log_type));
                                    LogUtils.i(TAG + "message.trade_id: " + message.trade_id);
                                    model.setOrder_sn(message.trade_id);
                                    model.setId(message.id);
                                    mDatas.add(model);
                                }
                                mDataSize += mDatas.size();
                                mAdapter.addAll(mDatas);
                                normalDataLayout();
                                //开启上拉加载更多

                            } else if (mDataSize == 0) {
                                noDataLayout();
                            }
                            //加款明细
                        } else if (typeDefine == 3) {
                            dataList = JSON.parseObject(addMoneyModel.data, AddMoneyModel.Data.class);
                            int pageSize = dataList.list.size();
                            //清除原数据,加载新数据,上拉加载
                            if (pageSize > 0) {
                                MessageItem model;
                                mDataSize = 0;
                                //重置
                                if (pageSize >= 10) {
                                    mPullRecyclerView.enableLoadMore(true);
                                }
                                pageGlobal = 2;
                                List<MessageItem> mDatas = new ArrayList<>();
                                for (AddMoneyModel.ListMessage message : dataList.list) {
                                    model = new MessageItem();
                                    model.setTitle(message.type);
                                    model.setSubTitle(message.money);
                                    model.setTime(message.add_time);
                                    model.setMessage(message.status);
                                    model.setImageResId(mipmapId(message.type));
                                    model.setOrder_sn(message.order_sn);
                                    model.setId(message.id);
                                    mDatas.add(model);
                                }
                                mDataSize += mDatas.size();
                                mAdapter.addAll(mDatas);
                                normalDataLayout();
                            } else if (mDataSize == 0) {
                                noDataLayout();
                            }
                        } else {
                            showToast("该功能暂未开启!");
                        }
                    } else {
                        try {
                            if (typeDefine == 1) {
                                dataAccountList = JSON.parseObject(addMoneyModel.data, AddMoneyModel.DataAccount.class);

                            } else if (typeDefine == 3) {
                                dataList = JSON.parseObject(addMoneyModel.data, AddMoneyModel.Data.class);

                            }
                        } catch (Exception e) {

                        }
                        //为空显示空页面
                        if (mDataSize == 0) {
                            noDataLayout();
                            mNullDataWarningTv.setText("暂无记录");
                        } else {
                            showToast(addMoneyModel.info);
                        }
                    }
                } else {
                    showToast("数据出错,请重试");
                }
            } catch (Exception ex) {

            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            if (activityIsDestory()) {
                return;
            }
            if (mDataSize != 0) {
                showToast(getResources().getString(R.string.connect_sever_error_toast));
            } else {
                errorLayout();
            }
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {

        }

        @Override
        public void onFinished() {
            if (activityIsDestory()) {
                return;
            }
            mPullRecyclerView.stopRefresh();
            mPullRecyclerView.stopLoadMore();
        }
    };

    @OnClick(R.id.requery_data_tv)
    public void onClick() {
        normalDataLayout();
        mPullRecyclerView.autoRefresh();
    }

    //上拉更新信息
    RequestCallBack callBackUp = new RequestCallBack() {
        @Override
        public void onSuccess(Object result) {
            if (activityIsDestory()) {
                return;
            }
            try {
                //json解析
                AddMoneyModel addMoneyModel = JSON.parseObject("" + result, AddMoneyModel.class);
                if (addMoneyModel != null) {
                    //有数据
                    if (addMoneyModel.status == 1) {
                        pageGlobal++;
                        if (typeDefine == 1) {
                            AddMoneyModel.DataAccount dataList = JSON.parseObject(addMoneyModel.data, AddMoneyModel.DataAccount.class);
                            int pageSize = dataList.list.size();
                            if (pageSize > 0) {
                                MessageItem model;
                                List<MessageItem> mDatas = new ArrayList<>();
                                for (AddMoneyModel.ListAccount message : dataList.list) {
                                    model = new MessageItem();
                                    model.setTitle(message.log_type);
                                    model.setSubTitle(message.money);
                                    model.setTime(message.time);
                                    model.setMessage(message.type);
                                    model.setImageResId(accountMipmapId(message.log_type));
                                    model.setOrder_sn(message.trade_id);
                                    model.setId(message.id);

                                    mDatas.add(model);
                                }
                                mAdapter.addAll(mDatas);
                                mDataSize += mDatas.size();
                                if (pageSize < 10) {
                                    mPullRecyclerView.enableLoadMore(false);
                                }
                            } else {
                                mPullRecyclerView.enableLoadMore(false);
                            }
                            //加款明细
                        } else if (typeDefine == 3) {
                            AddMoneyModel.Data dataList = JSON.parseObject(addMoneyModel.data, AddMoneyModel.Data.class);
                            int pageSize = dataList.list.size();
                            mDataSize += pageSize;
                            if (pageSize > 0) {
                                List<MessageItem> mDatas = new ArrayList<>();
                                MessageItem model;
                                for (AddMoneyModel.ListMessage message : dataList.list) {
                                    model = new MessageItem();
                                    model.setTitle(message.type);
                                    model.setSubTitle(message.money);
                                    model.setTime(message.add_time);
                                    model.setMessage(message.status);
                                    model.setImageResId(mipmapId(message.type));
                                    model.setOrder_sn(message.order_sn);
                                    model.setId(message.id);
                                    mDatas.add(model);
                                }
                                mAdapter.addAll(mDatas);
                            } else {
                                mPullRecyclerView.enableLoadMore(false);
                            }
                        }
                    } else {
                        try {
                            if (typeDefine == 1) {
                            } else if (typeDefine == 3) {
                                dataList = JSON.parseObject(addMoneyModel.data, AddMoneyModel.Data.class);
                            }
                        } catch (Exception e) {
                        }

                        mPullRecyclerView.enableLoadMore(false);
                    }
                } else {
                    showToast("数据出错,请重试");
                }
            } catch (Exception ex) {
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            if (activityIsDestory()) {
                return;
            }
            showToast(getResources().getString(R.string.connect_sever_error_toast));
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {

        }

        @Override
        public void onFinished() {
            if (activityIsDestory()) {
                return;
            }
            mPullRecyclerView.stopLoadMore();
            mPullRecyclerView.stopRefresh();
        }
    };

    //点击回调
    RequestCallBack callBackClick = new RequestCallBack() {
        @Override
        public void onSuccess(Object result) {
            if (activityIsDestory()) {
                return;
            }
            AccountDetailModel jsonAccountDetail = null;
            AddingMoneyDetailModel jsonDetail = null;

            //json解析
            if (typeDefine == 1) {
                jsonAccountDetail = JSON.parseObject("" + result, AccountDetailModel.class);

                //请求成功！
                if (jsonAccountDetail.getStatus() == 1) {

                    AccountDetailModel.DataBean.ListBean detailMessage = jsonAccountDetail.getData().getList();

                    dialog = new AddmoeyDialog(AddMoneyDetailActivity.this, detailMessage);

                    dialog.setCancelable(true);
                    dialog.setCanceledOnTouchOutside(true);// 屏蔽点击空拍dialog消失
                    dialog.showDialog();
                } else {
                    ToastUtils.showLong(jsonDetail.getInfo());
                }
            } else if (typeDefine == 3) {
                jsonDetail = JSON.parseObject("" + result, AddingMoneyDetailModel.class);

                //请求成功！
                if (jsonDetail.getStatus() == 1) {

                    AddingMoneyDetailModel.DataBean.ListBean detailMessage = jsonDetail.getData().getList();

                    dialog = new AddmoeyDialog(AddMoneyDetailActivity.this, detailMessage);

                    dialog.setCancelable(true);
                    dialog.setCanceledOnTouchOutside(true);// 屏蔽点击空拍dialog消失
                    dialog.showDialog();
                } else {
                    showToast(jsonDetail.getInfo());
                }
            } else {
                showToast("该功能暂未开启!");
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            if (activityIsDestory()) {
                return;
            }
            showToast("请检查网络");
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {
        }

        @Override
        public void onFinished() {
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 清空请求
        RequestTools.removeRequest(AddMoneyDetailActivity.class.getName());
        if (unbinder != null) {
            unbinder.unbind();
        }
    }

    //加入图标判断
    private int mipmapId(String message) {
        if (message.equals("转账(支付宝)")) {
            return R.mipmap.my_adding_alipay;
        } else if (message.equals("APP支付")) {
            return R.mipmap.my_adding_apppay;
        } else if (message.equals("转账(银行卡)")) {
            return R.mipmap.my_adding_transfer;
        } else if (message.equals("扫码支付")) {
            return R.mipmap.my_adding_smpay;
        } else if (message.equals("微信支付")) {
            return R.mipmap.mysetting_wxpay;
        } else if (message.equals("一网通")) {
            return R.mipmap.my_adding_bank_account;
        } else if (message.equals("财付通")) {
            return R.mipmap.my_adding_tencent;
        } else if (message.equals("网银(智付)")) {
            return R.mipmap.my_adding_bank;
        } else if (message.equals("支付宝")) {
            return R.mipmap.my_adding_alipay;
        }
        return R.mipmap.pay_turn;
    }

    //收支明细图标
    private int accountMipmapId(String message) {
        if (message.equals("转账记录")) {
            return R.mipmap.pay_zzjl;
        } else if (message.equals("在线充值")) {
            return R.mipmap.pay_online;
        } else if (message.equals("提现操作")) {
            return R.mipmap.pay_out;
        } else if (message.equals("管理员操作")) {
            return R.mipmap.pay_admin;
        } else if (message.equals("话费充值")) {
            return R.mipmap.pay_recharge;
        } else if (message.equals("开卡订单")) {
            return R.mipmap.pay_sim;
        } else if (message.equals("终端订单")) {
            return R.mipmap.pay_opencard;
        } else if (message.equals("流量充值")) {
            return R.mipmap.pay_gprs;
        } else if (message.equals("维系订单")) {
            return R.mipmap.pay_wx;
        } else if (message.equals("平台消费")) {
            return R.mipmap.pay_pc;
        } else if (message.equals("宽带订单")) {
            return R.mipmap.pay_kuandai;
        } else if (message.equals("开放平台")) {
            return R.mipmap.pay_openpc;
        } else if (message.equals("腾讯充值")) {
            return R.mipmap.pay_tencent;
        } else if (message.equals("红包")) {
            return R.mipmap.pay_bag;
        } else if (message.equals("转入押金")) {
            return R.mipmap.pay_turn;
        }
        return R.mipmap.pay_turn;
    }

    private static long OtherlastClickTime;

    private static boolean isFastDoubleClick(long lastClickTime) {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 1000 * 2) {
            return true;
        }
        return false;
    }
}